﻿CREATE PROCEDURE [dbo].[User_Login]
	@email nvarchar(256)
	,@passwordHash nvarchar(128)
	,@passwordSalt nvarchar(128)
AS
BEGIN

	DECLARE @userHashCode nvarchar(32)

	SET @userHashCode = CAST([dbo].[RandString](32) AS NVARCHAR(32))
	WHILE EXISTS (SELECT * FROM [dbo].[user_User] WHERE [HashCode] = @userHashCode)
	BEGIN
		SET @userHashCode = CAST([dbo].[RandString](32) AS NVARCHAR(32))
	END

	SET @email = LOWER(@email)
	IF EXISTS (SELECT * FROM [dbo].[user_User] WHERE Email = @email)
	BEGIN
		IF NOT EXISTS (SELECT * FROM [dbo].[user_User] WHERE Email = @email AND PasswordHash = @passwordHash AND PasswordSalt = @passwordSalt)
		BEGIN
			RAISERROR ('PasswordIncorrect',9,1)
			RETURN
		END
		ELSE
		BEGIN
			UPDATE [dbo].[user_User]
				 SET [HashCode] = @userHashCode
						,[ActivityDate] = GETDATE()
			 WHERE Email = @email AND PasswordHash = @passwordHash AND PasswordSalt = @passwordSalt

			 SELECT @userHashCode AS 'HashCode'

			 RETURN
		END
	END
	ELSE
	BEGIN
		RAISERROR ('EmailNotExist',9,1)
		RETURN
	END
END